<template>
  <div class="time-setting-panel">
    <el-divider content-position="left">时间设置</el-divider>

    <!-- 当前时间显示 -->
    <div class="current-time-display" v-if="isReady">
      <span class="span-title">当前时间：{{ formatTimeDisplay() }}</span>
      <el-button
        type="primary"
        size="small"
        :loading="isLoading"
        @click="handleRefresh"
        style="margin-left: 12px"
      >
        刷新
      </el-button>
    </div>

    <!-- 时间设置表单 -->
    <el-form
      ref="timeFormRef"
      :model="localTimeSetting"
      :rules="formRules"
      label-width="80px"
      class="time-setting-form"
      :disabled="isUpdating"
    >
      <el-row :gutter="16">
        <!-- 时区设置 -->
        <el-col :span="12">
          <el-form-item label="时区" prop="zone">
            <el-select v-model="localTimeSetting.zone" placeholder="选择时区" style="width: 100%">
              <el-option
                v-for="option in timezoneOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 年份设置 -->
        <el-col :span="12">
          <el-form-item label="年份" prop="year">
            <el-input-number
              v-model="localTimeSetting.year"
              :min="2000"
              :max="2099"
              :step="1"
              style="width: 100%"
              @change="handleYearMonthChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <!-- 月份设置 -->
        <el-col :span="12">
          <el-form-item label="月份" prop="month">
            <el-input-number
              v-model="localTimeSetting.month"
              :min="1"
              :max="12"
              :step="1"
              style="width: 100%"
              @change="handleYearMonthChange"
            />
          </el-form-item>
        </el-col>

        <!-- 日期设置 -->
        <el-col :span="12">
          <el-form-item label="日期" prop="day">
            <el-input-number
              v-model="localTimeSetting.day"
              :min="1"
              :max="maxDaysInMonth"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <!-- 小时设置 -->
        <el-col :span="8">
          <el-form-item label="小时" prop="hour">
            <el-input-number
              v-model="localTimeSetting.hour"
              :min="0"
              :max="23"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <!-- 分钟设置 -->
        <el-col :span="8">
          <el-form-item label="分钟" prop="minute">
            <el-input-number
              v-model="localTimeSetting.minute"
              :min="0"
              :max="59"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <!-- 秒设置 -->
        <el-col :span="8">
          <el-form-item label="秒" prop="sec">
            <el-input-number
              v-model="localTimeSetting.sec"
              :min="0"
              :max="59"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <el-form-item class="form-actions">
        <el-button type="info" size="small" @click="handleSetCurrentTime" :disabled="isUpdating">
          设为当前时间
        </el-button>
        <el-button type="warning" size="small" @click="handleReset" :disabled="isUpdating">
          重置
        </el-button>
        <el-button type="primary" size="small" :loading="isUpdating" @click="handleUpdate">
          整定
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 错误信息显示 -->
    <div v-if="errorMsg" class="error-message">
      <el-alert :title="errorMsg" type="error" :closable="true" @close="errorMsg = ''" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { useTimeSetting } from "@/composables";

// Props
interface Props {
  /** CPU 编号 */
  cpu?: number;
  /** 是否自动初始化 */
  autoInit?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  cpu: 1,
  autoInit: true,
});

// Emits
const emit = defineEmits<{
  refresh: [cpu: number];
  update: [cpu: number, success: boolean];
}>();

// 时间设置 Composable
const {
  localTimeSetting,
  isLoading,
  isUpdating,
  isReady,
  initTimeSetting,
  refreshTimeSetting,
  updateTimeSetting,
  resetLocalTimeSetting,
  setCurrentTime,
  formatTimeDisplay,
  getTimezoneOptions,
  getDaysInMonth,
  isValidDate,
} = useTimeSetting();

// 本地状态
const timeFormRef = ref<FormInstance>();
const errorMsg = ref<string>("");

// 计算属性
const timezoneOptions = computed(() => getTimezoneOptions());
const maxDaysInMonth = computed(() =>
  getDaysInMonth(localTimeSetting.value.year, localTimeSetting.value.month)
);

// 表单验证规则
const formRules: FormRules = {
  zone: [
    { required: true, message: "请选择时区", trigger: "change" },
    { type: "number", min: -12, max: 12, message: "时区必须在-12到12之间", trigger: "change" },
  ],
  year: [
    { required: true, message: "请输入年份", trigger: "blur" },
    { type: "number", min: 2000, max: 2099, message: "年份必须在2000到2099之间", trigger: "blur" },
  ],
  month: [
    { required: true, message: "请输入月份", trigger: "blur" },
    { type: "number", min: 1, max: 12, message: "月份必须在1到12之间", trigger: "blur" },
  ],
  day: [
    { required: true, message: "请输入日期", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入日期"));
        } else if (!isValidDate(localTimeSetting.value.year, localTimeSetting.value.month, value)) {
          callback(new Error(`该月份最多有${maxDaysInMonth.value}天`));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  hour: [
    { required: true, message: "请输入小时", trigger: "blur" },
    { type: "number", min: 0, max: 23, message: "小时必须在0到23之间", trigger: "blur" },
  ],
  minute: [
    { required: true, message: "请输入分钟", trigger: "blur" },
    { type: "number", min: 0, max: 59, message: "分钟必须在0到59之间", trigger: "blur" },
  ],
  sec: [
    { required: true, message: "请输入秒", trigger: "blur" },
    { type: "number", min: 0, max: 59, message: "秒必须在0到59之间", trigger: "blur" },
  ],
};

// 事件处理函数
const handleRefresh = async () => {
  try {
    await refreshTimeSetting(props.cpu);
    emit("refresh", props.cpu);
  } catch (e: any) {
    errorMsg.value = "刷新时间设置失败：" + e.message;
  }
};

const handleUpdate = async () => {
  if (!timeFormRef.value) return;

  try {
    const valid = await timeFormRef.value.validate();
    if (!valid) return;

    const result = await ElMessageBox.confirm("确定要整定时间设置吗？", "确认整定", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    if (result === "confirm") {
      const success = await updateTimeSetting(props.cpu);
      emit("update", props.cpu, success);
    }
  } catch (e: any) {
    if (e !== "cancel") {
      errorMsg.value = "整定时间设置失败：" + e.message;
    }
  }
};

const handleReset = () => {
  resetLocalTimeSetting();
  timeFormRef.value?.clearValidate();
  ElMessage.info("已重置为服务器时间");
};

const handleSetCurrentTime = () => {
  setCurrentTime();
  timeFormRef.value?.clearValidate();
  ElMessage.info("已设为当前时间");
};

const handleYearMonthChange = () => {
  // 当年份或月份改变时，检查日期是否有效
  nextTick(() => {
    const maxDays = getDaysInMonth(localTimeSetting.value.year, localTimeSetting.value.month);
    if (localTimeSetting.value.day > maxDays) {
      localTimeSetting.value.day = maxDays;
    }
    timeFormRef.value?.validateField("day");
  });
};

// 生命周期
onMounted(async () => {
  if (props.autoInit) {
    try {
      await initTimeSetting(props.cpu);
    } catch (e: any) {
      errorMsg.value = "初始化时间设置失败：" + e.message;
    }
  }
});

// 监听CPU变化
watch(
  () => props.cpu,
  async (newCpu) => {
    if (newCpu && props.autoInit) {
      try {
        await initTimeSetting(newCpu);
      } catch (e: any) {
        errorMsg.value = "切换CPU时间设置失败：" + e.message;
      }
    }
  }
);
</script>

<style scoped lang="scss">
.time-setting-panel {
  .current-time-display {
    margin-bottom: 16px;
    padding: 8px 0;

    .span-title {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }

  .time-setting-form {
    .form-actions {
      margin-top: 16px;
      text-align: right;

      .el-button {
        margin-left: 8px;
      }
    }
  }

  .error-message {
    margin-top: 16px;
  }
}
</style>
